<template>
  <textarea
    v-if="$attrs.type === 'textarea'"
    class="form-control"
    rows="10"
    :class="[error === '' ? '' : 'is-invalid']"
    :value="modelValue"
    @input="handlerInput"
    @blur="handlerBlur"
  ></textarea>
  <input
    v-else
    class="form-control"
    :class="[error === '' ? '' : 'is-invalid']"
    :value="modelValue"
    @input="handlerInput"
    @blur="handlerBlur"
  />
</template>

<script>
import bus from './bus';
import { onUnmounted, inject } from 'vue';
export default {
  name: 'KInput',
  props: {
    modelValue: String,
  },
  setup(props, context) {
    const error = inject('inputError');
    const handlerInput = (e) => {
      context.emit('update:modelValue', e.target.value);
    };

    const handlerBlur = () => {
      // 派发校验事件
      bus.$emit('input-validate');
    };

    onUnmounted(() => {
      bus.$off('input-validate');
    });
    return {
      error,
      handlerBlur,
      handlerInput,
    };
  },
};
</script>
